package com.heima.search.service.impl;

import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 删除搜索历史
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {

        if (dto == null || StringUtils.isBlank(dto.getHistoryId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        mongoTemplate.remove(Query.query(Criteria.where("id").is(dto.getHistoryId())), ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getPageSize() <= 0 || dto.getPageSize() > 10) {
            dto.setPageSize(10);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            //2 查询行为实体
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry == null) {
                log.warn("behaviorEntry is null :{}", dto);
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //3 查询历史记录
            List<ApUserSearch>  userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId")
                            .is(user.getId()))
                            .limit(10)
                            .with(Sort.by(Sort.Direction.DESC,"createdTime")),
                    ApUserSearch.class);


            //4 返回
            return ResponseResult.okResult(userSearchList);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    /**
     * 保存用户搜索历史记录
     * @param dto
     */
    @Override
    @Async
    public void insert(UserSearchDto dto) {

        log.info("ApUserSearchServiceImpl insert :{}", dto);

        // 1 参数检查
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            log.warn("ApUserSearchServiceImpl insert :{}", dto);
            return;
        }
        //2 查询行为实体
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            log.warn("behaviorEntry is null :{}", dto);
            return;
        }

        //3 查询关键词是否在历史记录存在
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(dto.getEntryId())
                .and("keyword").is(dto.getSearchWords())), ApUserSearch.class);

        //3.1 存在，更新历史记录的时间
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }

        //3.2 不存在
        // 判断当前集合中数据是否大于等于 10
        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(dto.getEntryId()))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime")), ApUserSearch.class);

        userSearch = new ApUserSearch();
        userSearch.setCreatedTime(new Date());
        userSearch.setEntryId(dto.getEntryId());
        userSearch.setKeyword(dto.getSearchWords());
        // 小于10 直接添加
        if (userSearchList == null || userSearchList.size() < 10) {
            mongoTemplate.save(userSearch);
        } else {
            // 否则 删除最后一条，加入最新的关键词
            ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);
            // 最后一条记录的id
            Query query = Query.query(Criteria.where("id").is(lastUserSearch.getId()));

            // 查找并替换
            mongoTemplate.findAndReplace(query, userSearch);
        }


        log.info("ApUserSearchServiceImpl insert success");
    }
}
